<template>
  <el-form :model="userForm" :rules="userRules" ref="userForm" label-width="95px"
           @keyup.enter.native="updateUserInfoHandle" @mouseleave.native="fourInputHandle(-1)">
    <el-form-item label="用户名称" prop="username">
      <el-input v-model="userForm.username" :readonly="updateBaseFlag" maxlength="20" placeholder="请输入用户名称" ref="username"
                @mouseenter.native="fourInputHandle(0)" class="u-input"></el-input>
      <el-button v-show="fourInput === 0 && updateBaseFlag" @click="toUpdateHandle(0)" type="text" class="text-btn">修改</el-button>
    </el-form-item>
    <el-form-item label="登录别名" prop="loginName">
      <el-input v-model="userForm.loginName" :readonly="updateBaseFlag" maxlength="20" placeholder="请输入登录别名" ref="loginName"
                @mouseenter.native="fourInputHandle(1)" class="u-input"></el-input>
      <el-button v-show="fourInput === 1 && updateBaseFlag" @click="toUpdateHandle(1)" type="text" class="text-btn">修改</el-button>
    </el-form-item>
    <el-form-item label="用户手机" prop="phone">
      <el-input v-model="userForm.phone" :readonly="updatePhoneFlag" maxlength="11" placeholder="请输入手机号" ref="phone"
                @mouseenter.native="fourInputHandle(2)" class="u-input"></el-input>
      <el-button v-show="fourInput === 2 && updatePhoneFlag" @click="toUpdateHandle(2)" type="text" class="text-btn">变更</el-button>
      <el-button v-show="fourInput === 2 && updatePhoneFlag && !!userForm.phone" :disabled="buttonLoad" type="text"
                 @click="unbindPhoneHandle" class="text-btn">解绑</el-button>
    </el-form-item>
    <el-form-item v-if="!updatePhoneFlag" label="短信验证码" prop="phoneCode">
      <el-input v-model="userForm.phoneCode" clearable maxlength="6"
                placeholder="请输入短信验证码" class="width25Percent"></el-input>
      <el-button type="text" size="medium" :disabled="phoneCodeLoad" @click="sendPhoneCodeHandle" class="text-btn">{{ sendPhoneCodeBtnText }}</el-button>
    </el-form-item>
    <el-form-item label="用户邮箱" prop="email">
      <el-input v-model="userForm.email" :readonly="updateEmailFlag" maxlength="20" placeholder="请输入邮箱号" ref="email"
                @mouseenter.native="fourInputHandle(3)" class="u-input"></el-input>
      <el-button v-show="fourInput === 3 && updateEmailFlag" @click="toUpdateHandle(3)" type="text" class="text-btn">变更</el-button>
      <el-button v-show="fourInput === 3 && updateEmailFlag && !!userForm.email" :disabled="buttonLoad" type="text"
                 @click="unbindEmailHandle" class="text-btn">解绑</el-button>
    </el-form-item>
    <el-form-item v-if="!updateEmailFlag" label="邮箱验证码" prop="emailCode">
      <el-input v-model="userForm.emailCode" clearable maxlength="6"
                placeholder="请输入邮箱验证码" class="width25Percent"></el-input>
      <el-button type="text" size="medium" :disabled="emailCodeLoad" @click="sendEmailCodeHandle" class="text-btn">{{ sendEmailCodeBtnText }}</el-button>
    </el-form-item>
    <el-form-item>
      <el-button :disabled="!updateType || buttonLoad" type="primary" @click="updateUserInfoHandle">修改</el-button>
      <el-button :disabled="!updateType || buttonLoad"  @click="cancelUpdateUserHandle">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
  export default {
    name: "user-info-update",
    data() {
      const phoneRegex = /^1(3[0-9]|4[5,7]|5[0-3,5-9]|6[2,5-7]|7[0-1,7-8]|8[0-9]|9[1,8-9])\d{8}$/
      const emailRegex = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/
      const checkUsername = (rule, value, callback) => {
        if (!value) {
          // 验证失败
          return callback(new Error("用户名称不能为空"))
        }
        callback();
      }
      let checkLoginName = (rule, value, callback) => {
        // 输入手机号或邮箱号后，登录别名可以不用输入
        let bool = !!this.userForm.phone || !!this.userForm.email
        // 输入手机号和邮箱号为空，用户别名输入不能为空
        bool = bool || !!value
        if (bool) {
          // 通过验证
          callback()
        } else {
          // 验证失败
          callback(new Error("未绑定手机号或者邮箱号，登录别名不能为空"))
        }
      };
      let checkPhone = (rule, value, callback) => {
        if (!this.updatePhoneFlag) {
          if (!value) {
            return callback(new Error("手机号不能为空"))
          }
          // 正则判断
          if (!phoneRegex.test(value)) {
            return callback(new Error("请输入正确的手机号码"))
          }
        }
        // 通过验证
        callback()
      };
      let checkEmail = (rule, value, callback) => {
        if (!this.updateEmailFlag) {
          if (!value) {
            return callback(new Error("邮箱号不能为空"))
          }
          // 正则判断
          if (!emailRegex.test(value)) {
            return callback(new Error("请输入正确的邮箱号码"))
          }
        }
        // 通过验证
        callback()
      };
      return {
        // 用户对象
        user: undefined,
        // 用户表单对象
        userForm: {
          // 用户名字
          username: '',
          // 用户手机号
          phone: '',
          // 短信验证码
          phoneCode: '',
          // 用户邮箱号
          email: '',
          // 邮箱验证码
          emailCode: '',
          // 用户登录别名
          loginName: ''
        },
        // 鼠标移入的输入框对应值
        fourInput: -1,
        // 用户数据修改类型[0-基本数据 1-基本数据 2-手机号 3-邮箱号]
        updateType: '',
        // 按钮是否可被点击[false-可以被点击 true-不可被点击]
        buttonLoad: false,
        // 获取短信验证码是否可被点击[false-可以被点击 true-不可被点击]
        phoneCodeLoad: false,
        // 获取邮箱验证码是否可被点击[false-可以被点击 true-不可被点击]
        emailCodeLoad: false,
        // 获取短信验证码按钮文字
        sendPhoneCodeBtnText: '获取验证码',
        // 获取验证码按钮文字
        sendEmailCodeBtnText: '获取验证码',
        // 系统用户表单校验规则
        userRules: {
          username: [
            { validator: checkUsername, trigger: 'blur' }
          ],
          loginName: [
            { validator: checkLoginName, trigger: 'blur' },
          ],
          phone: [
            { validator: checkPhone, trigger: 'blur' },
          ],
          phoneCode: [
            { validator: (rule, value, callback) => { !value ? callback(new Error("短信验证码不能为空")) : callback() }, trigger: 'blur' },
          ],
          email: [
            { validator: checkEmail, trigger: 'blur' },
          ],
          emailCode: [
            { validator: (rule, value, callback) => { !value ? callback(new Error("邮箱验证码不能为空")) : callback() }, trigger: 'blur' },
          ],
        }
      }
    },
    computed: {
      /**
       * 修改基础数据
       * @return {boolean} true-不能修改 false-可以修改
       */
      updateBaseFlag() {
        return this.updateType.indexOf('0') === -1 && this.updateType.indexOf('1') === -1;
      },
      /**
       * 修改手机号数据
       * @return {boolean} true-不能修改 false-可以修改
       */
      updatePhoneFlag() {
        return this.updateType.indexOf('2') === -1;
      },
      /**
       * 修改邮箱号数据
       * @return {boolean} true-不能修改 false-可以修改
       */
      updateEmailFlag() {
        return this.updateType.indexOf('3') === -1;
      },
    },
    methods: {
      // 初始化用户表单事件
      initUserInfoHandle(user) {
        this.user = user;
        let userForm = this.userForm;
        userForm.username = user.username
        userForm.loginName = user.loginName
        userForm.phone = user.phone
        userForm.email = user.email

        this.fourInput = -1;
        this.updateType = ''
        // 重置用户信息表单信息验证
        this.$refs.userForm.clearValidate();
      },
      // 更新用户信息事件
      updateUserInfoHandle() {
        // 按钮不可被点击
        this.buttonLoad = true
        this.$refs.userForm.validate((valid) => {
          if (!valid) {
            // 按钮恢复可点击
            this.buttonLoad = false
            return false;
          }
          let userForm = {...this.userForm};
          if (this.updateBaseFlag) {
            userForm.username = undefined;
            userForm.loginName = undefined;
          }
          if (this.updatePhoneFlag) {
            userForm.phone = undefined;
            userForm.phoneCode = undefined;
          }
          if (this.updateEmailFlag) {
            userForm.email = undefined;
            userForm.emailCode = undefined;
          }
          console.log('userForm', userForm);
          this.$axios.$post('/sys/user/info/update', this.userForm)
            .then(() => {
              this.notify('success', '信息修改成功', '成功修改用户个人信息')

              // 将用户名称写入Vuex中
              this.$store.commit('user/setUsername', this.userForm.username)
              // 向上传递事件，修改用户展示信息
              this.$emit('refresh-user-info', this.userForm)
            })
            .catch(() => {})
            .finally(() => {
              // 按钮恢复可点击
              this.buttonLoad = false
            })
        })
      },
      /**
       * 取消修改用户数据事件
       */
      cancelUpdateUserHandle() {
        let user = this.user;
        let userForm = this.userForm;
        userForm.username = user.username
        userForm.loginName = user.loginName
        userForm.phone = user.phone
        userForm.email = user.email

        this.fourInput = -1;
        this.updateType = ''

        this.$refs.userForm.clearValidate();
      },
      /**
       * 鼠标移入输入框事件
       * @param index 输入框所属下标值
       */
      fourInputHandle(index) {
        // console.log('index', index)
        this.fourInput = index;
      },
      /**
       * 切换到用户信息修改模式事件
       */
      toUpdateHandle(updateType) {
        // console.log('updateType', updateType)
        this.updateType = this.updateType + updateType;
        switch (updateType) {
          case 0:
            // 用户名称输入框获取焦点
            this.$refs.username.focus();
            break
          case 1:
            // 登录别名输入框获取焦点
            this.$refs.loginName.focus();
            break
          case 2:
            // 手机号输入框获取焦点
            this.$refs.phone.focus();
            break
          case 3:
            // 用户邮箱输入框获取焦点
            this.$refs.email.focus();
            break
          default:
            break
        }
      },
      /**
       * 发送短信验证码事件
       */
      sendPhoneCodeHandle() {
        // 发送短信验证码按钮不可被点击
        this.phoneCodeLoad = true;

        this.$refs.userForm.validateField('phone', (errorMsg) => {
          console.log('errorMsg', errorMsg)
          if (!!errorMsg) {
            this.$refs.phone.focus();
            // 发送短信验证码按钮恢复可点击
            this.phoneCodeLoad = false;
            return;
          }
          this.$axios.$get('/index/sms/send', { params: { phone: this.userForm.phone, validateType: 4 }})
            .then(() => {

              this.runPhoneCodeTimer()

              this.notify('success', '操作成功', '短信验证码发送成功。')
            })
            .catch(() => {
              // 发送短信验证码按钮恢复可点击
              this.phoneCodeLoad = false
            })
        })
      },
      /**
       * 发送邮箱验证码事件
       */
      sendEmailCodeHandle() {
        // 发送短信邮箱码按钮不可被点击
        this.emailCodeLoad = true;

        this.$refs.userForm.validateField('email', (errorMsg) => {
          if (!!errorMsg) {
            this.$refs.email.focus();
            // 发送邮箱验证码按钮恢复可点击
            this.emailCodeLoad = false;
            return;
          }
          this.$axios.$get('/index/mail/send', { params: { email: this.userForm.email, validateType: 5 }})
            .then(() => {

              this.runEmailCodeTimer()

              this.notify('success', '操作成功', '邮箱验证码发送成功。')
            })
            .catch(() => {
              // 发送邮箱验证码按钮恢复可点击
              this.emailCodeLoad = false
            })
        })
      },
      /**
       * 执行获取短信验证码定时器
       */
      runPhoneCodeTimer() {
        let num = 60
        this.sendPhoneCodeBtnText = num + "秒后可重试"
        const timer = setInterval(() => {
          num -= 1
          if (num === 0) {
            this.sendPhoneCodeBtnText = "获取验证码"
            // 发送短信验证码按钮恢复可点击
            this.phoneCodeLoad = false
            clearInterval(timer)
            return
          }
          this.sendPhoneCodeBtnText = num + "秒后可重试"
        }, 1000)
      },
      /**
       * 执行获取邮箱验证码定时器
       */
      runEmailCodeTimer() {
        let num = 60
        this.sendEmailCodeBtnText = num + "秒后可重试"
        const timer = setInterval(() => {
          num -= 1
          if (num === 0) {
            this.sendEmailCodeBtnText = "获取验证码"
            // 发送手机/邮箱验证码按钮解除禁用
            this.emailCodeLoad = false
            clearInterval(timer)
            return
          }
          this.sendEmailCodeBtnText = num + "秒后可重试"
        }, 1000)
      },
      /**
       * 解绑手机号事件
       */
      unbindPhoneHandle() {
        let userForm = this.userForm;
        if (!userForm.loginName && !userForm.email) {
          this.notify('', '温馨提示', '登录别名、手机号和邮箱不可同时为空，解绑失败')
          return
        }
        this.$confirm('您确定要进行手机号解绑操作吗, 是否继续?', '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 按钮禁用
          this.buttonLoad = true;

          return this.$axios.$post("/user-contact-flow/unbind/phone", { phone: userForm.phone });
        }).then(() => {
          this.notify('success', '操作成功', '手机号解除绑定操作成功');

          this.userForm.phone = '';

          // 向上传递事件，修改用户展示信息
          this.$emit('refresh-user-info', this.userForm)
        }).catch(() => {})
          .finally(() => {
            // 按钮恢复可点击
            this.buttonLoad = false;
          });
      },
      /**
       * 解绑邮箱事件
       */
      unbindEmailHandle() {
        let userForm = this.userForm;
        if (!userForm.loginName && !userForm.phone) {
          this.notify('', '温馨提示', '登录别名、手机号和邮箱不可同时为空，解绑失败')
          return
        }
        this.$confirm('您确定要进行邮箱解绑操作吗, 是否继续?', '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 按钮禁用
          this.buttonLoad = true;

          return this.$axios.$post("/user-contact-flow/unbind/email", { email: userForm.email });
        }).then(() => {
          this.notify('success', '操作成功', '邮箱解除绑定操作成功');

          this.userForm.email = '';

          // 向上传递事件，修改用户展示信息
          this.$emit('refresh-user-info', this.userForm)
        }).catch(() => {})
          .finally(() => {
            // 按钮恢复可点击
            this.buttonLoad = false;
          });
      },
    }
  }
</script>

<style scoped>
  .width25Percent {
    width: 25%;
  }
  .u-input {
    width: 35%;
  }
  .text-btn {
    font-size: 13px;
    margin-left: 10px;
  }
</style>
